package com.example.mobileshop;

import com.example.mobileshop.controller.UserController;
import com.example.mobileshop.models.User;

import android.app.Fragment;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RegisterFragment extends Fragment{
	private RegisterFragment(){}
	
	private static RegisterFragment instance = new RegisterFragment();
	
	public static RegisterFragment instance(){
		return instance; 
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_register, container, false);
        TextView loginScreen = (TextView) rootView.findViewById(R.id.link_to_login);
        Button btnRegister = (Button) rootView.findViewById(R.id.btnRegister);
        getActivity().getActionBar().setTitle(R.string.Register_screen);
        // Listening to register new account link
        loginScreen.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View v) {
                // Switching to Register screen
            	Fragment fragment = LoginFragment.instance();             	
    			FragmentManager fragmentManager = getFragmentManager();
    			fragmentManager.beginTransaction()
    					.replace(R.id.frame_container, fragment).commit();        			        		
            }
        });        
        
        btnRegister.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {				
				EditText txtConfirmPassword = (EditText) rootView.findViewById(R.id.reg_confirmpassword);
				EditText txtEmail = (EditText) rootView.findViewById(R.id.reg_email);
				EditText txtPassword = (EditText) rootView.findViewById(R.id.reg_password);
				User user = new User();				
				user.setEmail(txtEmail.getText().toString());
				user.setPassword(txtPassword.getText().toString());
				new InsertUser().execute(user); 
			}
		});
        return rootView;        
    }
	
	/**
     * Async task class to get json by making HTTP call
     * */
    private class InsertUser extends AsyncTask<User, Void, Void> {    	    	    	     	    	
    	@Override
        protected void onPreExecute() {
            super.onPreExecute();             
        }

		@Override
		protected Void doInBackground(User... arg0) {		
			UserController userController = new UserController();
			String result = userController.createNewUser(arg0[0]);			
			return null;
		}
		
		@Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);                   
        }    	
    }
}